package com.manager.common.job;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.manager.common.utils.DataTools;
import org.springframework.beans.factory.annotation.Value;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class GetDockerContainerLogsInfoThread extends Thread{

    private String ip;

    private Integer port;

    private String password;

    private String userName;

    private  String containerId;

    public GetDockerContainerLogsInfoThread(String ip, Integer port, String password, String userName,String containerId) {
        this.ip = ip;
        this.port = port;
        this.password = password;
        this.userName = userName;
        this.containerId = containerId;
    }

    @Override
    public void run() {
           JSch jsch = new JSch();
           Session session = null;

           try {
               session = jsch.getSession(userName, ip, port);
               session.setPassword(password);

               Properties sshConfig = new Properties();
               sshConfig.put("StrictHostKeyChecking", "no");

               session.setConfig(sshConfig);

               session.connect(60 * 1000);

               String buffer;
               InputStreamReader isr = null;
               BufferedReader reader = null;

               Channel channel = session.openChannel("exec");
               ChannelExec channelExec = (ChannelExec) channel;


               channel.setInputStream(null);

               InputStream successIn = channelExec.getInputStream();

               channelExec.setCommand("docker logs -f " + containerId +" --tail=100 ");
               channel.connect();

               isr = new InputStreamReader(successIn, StandardCharsets.UTF_8);
               reader = new BufferedReader(isr);

               while ((buffer = reader.readLine()) != null) {
                   DataTools.putDockerContainerLog(containerId, buffer,channel);
               }

               isr.close();
               reader.close();

               channelExec.disconnect();

               channel.disconnect();

           }catch (Exception e){
               e.printStackTrace();
           }
    }
}
